<template>
  <div class="">
    <public-dialog :title="titleName" width="50%" dialogCenter :visible="visible" confirmButtonTitle="下载"
      @update:visible="onVisibleChange" @onConfirm="confirmHandler">
      <div style="text-align: center;">
        <div style="display: flex;align-items: center;justify-content: center;" ref="docxContentRef" id="demoDocContainer"/>
        <div v-if="!fileUrl">
          <span>暂无发票</span>
        </div>
      </div>
    </public-dialog>
  </div>
</template>

<script setup>
import {ref} from "vue";
import PublicDialog from "@/components/PublicDialog.vue";
import { ElNotification } from "element-plus"
import {blobToFile, downloadFile} from "@/common/utils/GlobalUtils";
import PDFObject from "pdfobject";

let titleName = ref("");
let visible = ref(false);
let fileUrl = ref("");

let onVisibleChange = (booleanValue) => {
  if (!booleanValue) {
    fileUrl.value = "";
  }
  visible.value = booleanValue;
};


const  downFile = async (downUrl) => {
        const response = await fetch(downUrl); // 替换为实际的OFD文件URL
        const blob = await response.blob();
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'example.ofd';
        a.click();
        URL.revokeObjectURL(url);
}

let confirmHandler = () => {
  if (!fileUrl.value) {
     return ElNotification.warning("暂无可下载发票");
  }
    let type = fileUrl.value.substring(fileUrl.value.lastIndexOf('.')).toLowerCase();
    if(type==='.pdf'){
      // downloadFile(fileUrl.value,'发票');
     window.open(fileUrl.value);
    }
    if(type==='.ofd'){
        downFile(fileUrl.value);
    }
};

const getWord = async (fileUrlKey) => {
    const response = await fetch(fileUrlKey); // 替换为实际的OFD文件URL
    const res = await response.blob();
    let blob = new Blob([res], {
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8'
    });
    // 将blob转换为file
    let file = blobToFile(blob,new Date().getTime(),'application/pdf');
    // 将file转换为dataUrl
    let dataUrl = URL.createObjectURL(file);
    PDFObject.embed(dataUrl, '#demoDocContainer', {width: '100%', heigth: '100%'});
    setTimeout(() => {
        URL.revokeObjectURL(dataUrl);
    }, 1000);
}

let openHandler = (title, row) => {
  titleName.value = title;
  fileUrl.value = row.fileAddress;
  getWord(fileUrl.value);
  visible.value = true;
};

defineExpose({
  openHandler
});
</script>


<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
}

#demoDocContainer{
  height: 65vh !important;
}
</style>
